<template>
  <div class="dv3">

    <div style="margin:5%;color: #ee0a24;text-align: left;" @click="exit()">《《《  返回
    </div>
      <div>
      <van-cell-group inset>
        <van-field
            v-model="nickname"
            center
            clearable
            label="昵称"
            placeholder="请输入你在聊天室的昵称"
        >
          <template #button >

            <van-button size="small" type="primary"  @click="connect()">连接聊天室</van-button>
          </template>
        </van-field>
      </van-cell-group>
    </div>
    <!--  2.聊天区-->
    <div class="dv1" >

      <div style="float: left ;margin-top: 3px " >
        <van-cell-group >
        <van-cell :title="c" v-for=" c in chats" />
      </van-cell-group>
      </div>
    </div>
    <!--  3.底部-->
    <div class="dv2" >
      <van-field
          v-model="msg"
          center
          clearable
          label="聊天内容："
          placeholder="请输入内容"
      >
        <template #button>
          <van-button size="small" type="primary" @click="send()">发送</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
var ws;
export default {
  name: "ChatView",
  data(){
    return{
      chats:[],
      nickname:"",
      msg:""
    }
  },
  methods:{
    connect(){
      //连接WebSocket
      if ("WebSocket" in window)
      {
        // 打开一个 web socket
        ws = new WebSocket("ws://8.142.160.101:8082/server/chat/"+this.nickname);
        ws.onopen = function()
        {
          //console.log("连接服务器")
        };

        ws.onmessage = (evt)=>
        {
          this.chats.push(evt.data);
          //console.log("数据已接收...:"+evt.data);
        };
        ws.onclose = function()
        {
          // 关闭 websocket
          alert("连接已关闭...");
        };
      }
    },
    send(){
      //发送消息
      ws.send(this.msg);
      this.msg="";
    },
    exit(){
        this.$router.push("/community")
    }

  }
}
</script>

<style scoped>
.dv1{
  float: left;
}
.dv2{
  float: left;
  position: fixed;
  bottom: 2px;
  width: 100%;

}
.dv3{
  height: 100%;
}
</style>
